package com.zl.basis.component;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

public class ServiceUtil {

    public static boolean startService(Context mContext, String action, String category) {
        Intent intent = getServiceIntent(mContext, action, category);
        if (null != intent) {
            mContext.startService(intent);
            return true;
        }
        return false;
    }

    public static boolean startService(Context mContext, String action) {
        return startService(mContext, action, Intent.CATEGORY_DEFAULT);
    }

    public static boolean startService(Context mContext, String... actions) {
        if (null == actions || actions.length < 1) {
            return false;
        }
        boolean success = false;
        for (String action : actions) {
            success = startService(mContext, action);
        }
        return success;
    }

    public static boolean stopService(Context mContext, String action, String category) {
        Intent intent = getServiceIntent(mContext, action, category);
        if (null != intent) {
            mContext.stopService(intent);
            return true;
        }
        return false;
    }

    public static boolean stopService(Context mContext, String action) {
        return stopService(mContext, action, Intent.CATEGORY_DEFAULT);
    }

    public static boolean stopService(Context mContext, String... actions) {
        if (null == actions || actions.length < 1) {
            return false;
        }
        boolean success = false;
        for (String action : actions) {
            success = stopService(mContext, action);
        }
        return success;
    }

    public static Intent getServiceIntent(Context mContext, String action, String category) {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.addCategory(category);
        PackageManager pm = mContext.getPackageManager();
        ResolveInfo info = pm.resolveService(intent, 0);
        if (info != null) {
            String packageName = info.serviceInfo.packageName;
            String serviceName = info.serviceInfo.name;
            ComponentName componentName = new ComponentName(packageName, serviceName);
            intent.setComponent(componentName);
            return intent;
        }
        return null;
    }

}
